function getRandom (min, max) {
  return Math.floor(Math.random() * (max - min + 1) + min)
}

// 计算Task状态
export function computeTaskStatus (taskInfo) {
  let computedStatus = {}
  if (taskInfo.state === 'JOB_NOT_FOUND') {
    computedStatus.val = 'N/A'
    computedStatus.className = 'status-stop'
  } else if (taskInfo.state === 'WAITING') {
    if (taskInfo.executionType === 'STOP') {
      computedStatus.val = '停止'
      computedStatus.className = 'status-stop'
    } else {
      computedStatus.val = '等待'
      computedStatus.className = 'status-wait'
    }
  } else if (taskInfo.state === 'RUNNING') {
    if (taskInfo.executionType === 'STOP') {
      computedStatus.val = '停止'
      computedStatus.className = 'status-stop'
    } else {
      computedStatus.val = '运行中'
      computedStatus.className = 'status-run'
    }
  } else if (taskInfo.state === 'SUCCEEDED') {
    computedStatus.val = '成功'
    computedStatus.className = 'status-success'
  } else if (taskInfo.state === 'FAILED') {
    computedStatus.val = '失败'
    computedStatus.className = 'status-failure'
  } else if (taskInfo.state === 'STOPPED') {
    computedStatus.val = '停止'
    computedStatus.className = 'status-stop'
  } else {
    computedStatus.val = '未知'
    computedStatus.className = 'status-stop'
  }
  return computedStatus
}

// 计算相差时间
export function computedDuration (startTime, endTime) {
  if (startTime) {
    if (startTime === null) {
      return 0
    }
    if (endTime === null) {
      endTime = Date.now()
    }
    let elapsedTime = Math.round(Math.max(0, endTime - startTime) / 1000)
    let result = ''
    const elapsedDay = parseInt(elapsedTime / (24 * 60 * 60))
    if (elapsedDay > 0) {
      result += elapsedDay + 'd '
    }
    const elapsedHour = parseInt((elapsedTime % (24 * 60 * 60)) / (60 * 60))
    if (result != '' || (result == '' && elapsedHour > 0)) {
      result += elapsedHour + 'h '
    }
    const elapsedMinute = parseInt(elapsedTime % (60 * 60) / 60)
    if (result != '' || (result == '' && elapsedMinute > 0)) {
      result += elapsedMinute + 'm '
    }
    const elapsedSecond = parseInt(elapsedTime % 60)
    result += elapsedSecond + 's'
    return result
  } else {
    return '--'
  }
}

// 计算相差时间
export function computedDurTime (time) {
  if (time) {
    // let elapsedTime = Math.round(time / 1000)
    let elapsedTime = time
    let result = ''
    const elapsedDay = parseInt(elapsedTime / (24 * 60 * 60))
    if (elapsedDay > 0) {
      result += elapsedDay + 'd '
    }
    const elapsedHour = parseInt((elapsedTime % (24 * 60 * 60)) / (60 * 60))
    if (result != '' || (result == '' && elapsedHour > 0)) {
      result += elapsedHour + 'h '
    }
    const elapsedMinute = parseInt(elapsedTime % (60 * 60) / 60)
    if (result != '' || (result == '' && elapsedMinute > 0)) {
      result += elapsedMinute + 'm '
    }
    const elapsedSecond = parseInt(elapsedTime % 60)
    result += elapsedSecond + 's'
    return result
  } else {
    return '--'
  }
}

export function shuffle (arr) {
  let _arr = arr.slice()
  for (let i = 0; i < _arr.length; i++) {
    let j = getRandom(0, i)
    let t = _arr[i]
    _arr[i] = _arr[j]
    _arr[j] = t
  }
  return _arr
}

/*
  description：节流函数，通过控制每次事件执行的时间间隔控制短时间多次执行方法
  func: 要执行的方法
  delay: 每次事件执行的推迟时间（毫秒）
*/
export function throttle (func, wait) {
  var lastTime = 0
  return function () {
    var nowTime = new Date().getTime()
    if (nowTime - lastTime > wait) {
      func.apply(this, arguments)
      lastTime = nowTime
    }
  }
}

/*
  description：防抖函数，通过推迟每次事件执行的时间来减少不必要的查询
  func: 要执行的方法
  delay: 每次事件执行的推迟时间（毫秒）
*/
export function debounce (func, delay) {
  var timer
  return function (...args) {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      func.apply(this, args)
    }, delay)
  }
}

// 数组求和
export function arraySum (arr) {
  if (arr.length === 0) {
    return 0
  } else if (arr.length === 1) {
    return Number(arr[0])
  } else {
    return Number(arr[0]) + arraySum(arr.slice(1))
  }
}

// 数组按对象属性排序
export function arraySortBy (arr, by) {
  function sortBy (a, b) {
    return a[by] - b[by]
  }
  return arr.sort(sortBy)
}

// 数组按对象日期属性排序(des: true 降序)
export function arraySortByDate (arr, by, des) {
  function sortBy (a, b) {
    let aa = new Date(a[by])
    let bb = new Date(b[by])
    if (des) {
      return aa - bb
    } else {
      return bb - aa
    }
  }
  return arr.sort(sortBy)
}

// 深拷贝对象
export function deepCopy (obj) {
  if (typeof obj !== 'object') {
    return obj
  }
  var newobj = {}
  for (var attr in obj) {
    newobj[attr] = deepCopy(obj[attr])
  }
  return newobj
}

// 获取cookie、
export function getCookie () {
  var arr; var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)')
  if (arr === document.cookie.match(reg))
    {return (arr[2])}
  else
    {return null}
}

// inArray
export function inArray (search, array) {
  for (var i in array) {
    if (array[i] == search) {
      return true
    }
  }
  return false
}

// 设置cookie,增加到vue实例方便全局调用
export function setCookie (c_name, value, expiredays, path) {
  var exdate = new Date()
  exdate.setDate(exdate.getDate() + expiredays)
  document.cookie = c_name + '=' + escape(value) + ((expiredays == null) ? '' : ';expires=' + exdate.toGMTString()) + (path ? ';path=/' : `;path=${path}`)
}

// 删除cookie
export function delCookie (name) {
  var exp = new Date()
  exp.setTime(exp.getTime() - 1)
  var cval = getCookie(name)
  if (cval != null)
    {document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString()}
}

// 时间戳转字符串
// n=1 显示2011-05-23 15:54:26, n=2: 显示2011-05-23
export function timeToStr (timestamp, n) {
  if (timestamp == undefined) return '-';
  var update = new Date(timestamp)
  var year = update.getFullYear()
  var month = (update.getMonth() + 1 < 10) ? ('0' + (update.getMonth() + 1)):(update.getMonth() + 1)
  var day = (update.getDate() < 10) ? ('0' + update.getDate()):(update.getDate())
  var hour = (update.getHours() < 10) ? ('0' + update.getHours()):(update.getHours())
  var minute = (update.getMinutes() < 10) ? ('0' + update.getMinutes()):(update.getMinutes())
  var second = (update.getSeconds() < 10) ? ('0' + update.getSeconds()):(update.getSeconds())
  if (n === 1) {
    return (year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second)
	} else if (n === 2) {
    return (year + '-' + month + '-' + day)
	} else{
    return 0
	}
}

// 最近n个月时间获取
export function getnMonthBefor (n) {
  var resultDate, year, month, date, hms
  var currDate = new Date()
  year = currDate.getFullYear()
  month = currDate.getMonth() + 1
  date = currDate.getDate()
  hms = currDate.getHours() + ':' + (currDate.getMinutes() < 10 ? '0' + currDate.getMinutes() : currDate.getMinutes()) + ':' + (currDate.getSeconds() < 10 ? '0' + currDate.getSeconds() : currDate.getSeconds())
  if (month <= n) {
    month += 12 - n
    year--
  } else {
    month -= n
  }
  month = (month < 10) ? ('0' + month) : month
  resultDate = year + '-' + month + '-' + date + ' ' + hms
  return resultDate
}

// 获得密码强度
export function pwdIntensity (pwd) {
  let intensity = 0
  if (pwd.length < 6 || pwd.length > 32) {
    return intensity
  }
  if (/[a-z]/.test(pwd)) {
    intensity++
  }
  if (/[A-Z]/.test(pwd)) {
    intensity++
  }
  if (/[0-9]/.test(pwd)) {
    intensity++
  }
  if (/[`_~!@#$%^&;.*()-+=|"':,?]/.test(pwd)) {
    intensity++
  }
  return intensity
}

// 随机字符串生成
export function randomString (len) {
  len = len || 32
  var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  var maxPos = $chars.length
  var str = ''
  for (var i = 0; i < len; i++) {
    str += $chars.charAt(Math.floor(Math.random() * maxPos))
  }
  return str
}

var docCookies = {
  getItem: function (sKey) {
    return decodeURIComponent(document.cookie.replace(new RegExp('(?:(?:^|.*;)\\s*' + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, '\\$&') + '\\s*\\=\\s*([^;]*).*$)|^.*$'), '$1')) || null
  },
  setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
    if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false }
    var sExpires = '';
    if (vEnd) {
      switch (vEnd.constructor) {
        case Number:
          sExpires = vEnd === Infinity ? '; expires=Fri, 31 Dec 9999 23:59:59 GMT' : '; max-age=' + vEnd
          break;
        case String:
          sExpires = '; expires=' + vEnd
          break;
        case Date:
          sExpires = '; expires=' + vEnd.toUTCString()
          break;
      }
    }
    document.cookie = encodeURIComponent(sKey) + '=' + encodeURIComponent(sValue) + sExpires + (sDomain ? '; domain=' + sDomain : '') + (sPath ? '; path=' + sPath : '/') + (bSecure ? '; secure' : '')
    return true
  },
  removeItem: function (sKey, sPath, sDomain) {
    if (!sKey || !this.hasItem(sKey)) { return false }
    document.cookie = encodeURIComponent(sKey) + '=; expires=Thu, 01 Jan 1970 00:00:00 GMT' + (sDomain ? '; domain=' + sDomain : '') + (sPath ? '; path=' + sPath : '/')
    return true
  },
  hasItem: function (sKey) {
    return (new RegExp('(?:^|;\\s*)' + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, '\\$&') + '\\s*\\=')).test(document.cookie)
  },
  keys: /* optional method: you can safely remove it! */ function () {
    var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, '').split(/\s*(?:\=[^;]*)?;\s*/)
    for (var nIdx = 0; nIdx < aKeys.length; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]) }
    return aKeys
  }
}

export { docCookies }

// 获取相差多少天
export function getOffsetDays (time) {
  var today = new Date()
  today.setHours(0)
  today.setMinutes(0)
  today.setSeconds(0)
  today.setMilliseconds(0)
  var offsetTime = Math.abs(time - today)
  return Math.ceil(offsetTime / (3600 * 24 * 1e3))
}
// 千分符转化 保留n位小数
export function fmoney (s, n) {
  n = n > 0 && n <= 20 ? n : 2
  s = parseFloat((s + '').replace(/[^\d\.-]/g, '')).toFixed(n) + ''
  var l = s.split('.')[0].split('').reverse();


var r = s.split('.')[1]
  var t = ''
  for (var i = 0; i < l.length; i++) {
    t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? ',' : '')
  }
  return t.split('').reverse().join('') + '.' + r
}

// 支持预览的文件类型
export function verifyFileType (fileType) {
  let result = false
  if (/(?:ini|conf|json|txt|py|java|js|ejs|vue|asp|ts|html|css|scss|less|styl|c|go|sql|md|xml|lock|HEAD|sample|gitignore|config|master|yml|map)$/.test(fileType)) result = true
  return result
}
